<template>
  <Dialog :visible="visibleBindSms" width="60%"
          @cancel="visibleClose"
          :title="rows.appName + ' - ' +  $t('绑定短信')"
          :footer="false"
          @close="visibleClose">
    <el-row :gutter="24" style="margin:0">
      <el-form label-width="80px">
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('短信名称')">
            <el-input v-model="page.smsName"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('短信类型')">
            <el-select style="width: 100%" v-model="page.type" clearable>
              <el-option v-for="item in smsTypeList" :key="item.key" :value="item.key" :label="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('状态')">
            <el-select style="width: 100%" v-model="page.status" clearable>
              <el-option :value="1" :label="$t('启用')"></el-option>
              <el-option :value="0" :label="$t('禁用')"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('修改时间')">
            <el-date-picker
                v-model="page.updateTimeValue"
                style="width: 100%"
                unlink-panels
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="~"
                :start-placeholder="$t('开始时间')"
                :end-placeholder="$t('结束时间')">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-button type="primary" @click="getTableData">{{ $t('查询') }}</el-button>
          <el-button @click="resetSearch">{{ $t('重置') }}</el-button>
        </el-col>
      </el-form>
    </el-row>
    <div style="margin-bottom:15px;text-align: right">
      <el-button type="primary" v-show="$permiss[1553]" @click="copySmsApp">{{ $t('复制到其他APP') }}</el-button>
    </div>
    <Table :page="page" :table-data="tableData" @handleCurrentChange="handleCurrentChange"
           :selection="true"
           row-key="id"
           @handleSelectionChange="(value)=>{
             selectSmsRows = value
           }"
           :select-rows="selectSmsRows"
           @handleSizeChange="handleSizeChange" :table-column="tableColumn">
      <template slot="status" slot-scope="{row}">
        <el-switch :value="row.status === 1" @change="changeStatus(row)" :disabled="!$permiss[1623]"/>
      </template>
      <template slot="type" slot-scope="{row}">
        {{ smsTypeList.find(s => s.key === row.type).value }}
      </template>
      <template slot="handle" slot-scope="{row}">
        <el-button type="text" @click="editSms(row)" v-show="$permiss[1551]">{{ $t('编辑') }}</el-button>
      </template>
    </Table>
    <Dialog :append-body="true" :visible.sync="visibleEdit"
            @close="clearForm"
            @cancel="visibleEdit = false"
            @confirm="editSmsConfirm"
            :title="$t('编辑短信')">
      <el-form :model="form" ref="form" label-width="80px">
        <el-form-item :label="$t('短信名称')" prop="smsName" :rules="[
              {required: true,trigger:'blur',message:$t('不能为空')}
          ]">
          <el-input style="width: 250px" v-model="form.smsName"/>
        </el-form-item>
        <el-form-item :label="$t('短信名称')" prop="type" :rules="[
              {required: true,trigger:'change',message:$t('请选择')}
          ]">
          <el-select v-model="form.type" clearable>
            <el-option v-for="item in smsTypeList" :key="item.key" :value="item.key" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('短信内容')" prop="smsStencil" :rules="[
              {required: true,trigger:'blur',message:$t('不能为空')}
          ]">
          <el-input type="textarea" :rows="6" maxlength="500" v-model="form.smsStencil"/>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    复制短信给APP-->
    <Dialog :append-body="true" :visible.sync="visibleCopySms"
            @close="selectProductList = []"
            @cancel="visibleCopySms = false"
            @confirm="copySmsConfirm"
            width="500px"
            :title="$t('复制短信给选中的APP')">
      <el-select v-model="selectProductList" style="width: 100%" clearable multiple>
        <el-option v-for="item in productList" :label="item.appName" :key="item.productId"
                   :value="item.productName"></el-option>
      </el-select>
    </Dialog>
    <!-- 编辑短信-->
    <Dialog :append-body="true" :visible.sync="visibleEdit"
            @close="clearForm"
            @cancel="visibleEdit = false"
            @confirm="editSmsConfirm"
            ref="editForm"
            :title="$t('编辑短信')">
      <el-form :model="form" ref="form" label-width="80px">
        <el-form-item :label="$t('短信名称')" prop="smsName" :rules="[
              {required: true,trigger:'blur',message:$t('不能为空')}
          ]">
          <el-input style="width: 100%" :disabled="true" v-model="form.smsName"/>
        </el-form-item>
        <el-form-item :label="$t('短信类型')" prop="type" :rules="[
              {required: true,trigger:'change',message:$t('请选择')}
          ]">
          <el-select v-model="form.type" :disabled="true" clearable>
            <el-option v-for="item in smsTypeList" :key="item.key" :value="item.key" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('短信内容')" prop="smsStencil" :rules="[
              {required: true,trigger:'blur',message:$t('不能为空')}
          ]">

          <el-input ref="textarea" type="textarea" @contextmenu.prevent.native="showSmsVarCard" :rows="6"
                    @blur="smsInsertVisible = false"
                    maxlength="500" v-model="form.smsStencil"/>
          <el-alert
              style="margin-top:10px;line-height: 22px"
              title="在短信内容文本框中，点击鼠标右键可插入变量值"
              type="info"
              :closable="false"
              show-icon>
          </el-alert>
          <transition name="el-fade-in-linear">
            <el-card :body-style="{padding:'0px'}" class="smsInsertVisible" v-show="smsInsertVisible"
                     style="position: absolute"
                     :style="{left:panelLeft+'px',top:panelTop+'px'}">
              <ul style="text-align:center">
                <li v-for="item in smsVarList" :key="item.id" @click="smsVarChange(item.parameter)">{{ item.name }}</li>
              </ul>
            </el-card>
          </transition>
        </el-form-item>
      </el-form>

    </Dialog>

  </Dialog>
</template>

<script>
import {fetchProductSmsList, productSmsUpdate, productSmsCopy, selectSmsVarList,updateSmsStatus} from "@/api/product"
import {selectProduct} from "@/api/system";
import {dateFormatSection} from "@/utils/tools";

export default {
  name: "bindSms",
  props: {
    visibleBindSms: {},
    rows: {}
  },
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      tableColumn: [
        {label: this.$t('短信名称'), prop: 'smsName',},
        {label: this.$t('短信类型'), prop: 'type', slot: 'type'},
        {label: this.$t('短信内容'), prop: 'smsStencil', minWidth: 200},
        {label: this.$t('修改时间'), prop: 'updateTime', minWidth: 150},
        {label: this.$t('状态'), prop: 'status', slot: 'status'},
        {label: this.$t('操作'), slot: 'handle',},
      ],
      smsTypeList: [
        {key: 1, value: this.$t('短信验证码')},
        {key: 2, value: this.$t('到期提醒')},
        {key: 3, value: this.$t('展期')},
        {key: 4, value: this.$t('营销短信')},
        {key: 5, value: this.$t('还款短信')},
        {key: 6, value: this.$t('放款短信')},
        {key: 7, value: this.$t('订单短信')},
        {key: 8, value: this.$t('逾期提醒')},
        {key: 9, value: this.$t('优惠券短信')},
      ],
      form: {},
      visibleEdit: false,
      visibleCopySms: false,
      selectProductList: [],
      selectSmsRows: [],
      productList: [],
      smsInsertVisible: false,
      panelLeft: 0,
      panelTop: 0,
      smsVarList: [],
    }
  },
  watch: {
    visibleBindSms(value) {
      if (value) {
        this.getTableData()
        selectProduct().then(res => {
          this.productList = res.data.filter(item => {
            return item.productName !== this.rows.productName
          })
        })
      }
    }
  },
  methods: {
    async getTableData() {
      const [startTime, endTime] = dateFormatSection(this.page.updateTimeValue)
      const params = {
        ...this.page,
        productName: this.rows.productName,
        startTime, endTime
      }
      delete params.updateTimeValue
      const res = await fetchProductSmsList(params)
      if (res.code === 1) {
        const {total, list} = res.data
        this.page.total = total
        this.tableData = list
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    async changeStatus({id, status}) {
      this.$confirm(this.$t('当前状态改变后对业务可能造成影响和风险,请慎重操作'), this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const res = await updateSmsStatus({
          id,
          status: status === 1 ? 0 : 1
        })
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.getTableData()
        }
      }).catch(() => {
      })
    },
    visibleClose() {
      this.$emit('update:visibleBindSms', false)
    },
    copySmsApp() {
      if (this.selectSmsRows.length <= 0) return this.$message.error(this.$t('请先选择短信!'))
      this.visibleCopySms = true
    },
    async editSms(row) {
      const res = await selectSmsVarList()
      if (res.code === 1) {
        this.smsVarList = res.data
      }
      this.form = {...row}
      this.visibleEdit = true
    },

    showSmsVarCard(e) {
      const menuMinWidth = 105
      const offsetLeft = this.$refs.textarea.$el.getBoundingClientRect().left
      const offsetTop = this.$refs.textarea.$el.getBoundingClientRect().top
      const offsetWidth = this.$refs.textarea.$el.offsetWidth
      const maxLeft = offsetWidth - menuMinWidth
      const left = e.clientX - offsetLeft + 15
      if (left > maxLeft) {
        this.panelLeft = maxLeft
      } else {
        this.panelLeft = left
      }
      this.panelTop = e.clientY - offsetTop + 15
      this.smsInsertVisible = true
    },
    smsVarChange(value) {
      let element = this.$refs.textarea.$el.children[0]; // 获取到指定标签
      let startPos = element.selectionStart; // 获取光标开始的位置
      let endPos = element.selectionEnd; // 获取光标结束的位置
      if (startPos === undefined || endPos === undefined) return; // 如果没有光标位置 不操作
      let oldTxt = this.form.smsStencil
      let result = oldTxt.substring(0, startPos) + value + oldTxt.substring(endPos); // 将文本插入
      this.form.smsStencil = result
      this.smsInsertVisible = false
    },
    clearForm() {
      this.$refs.form.resetFields()
      this.form = {}
    },
    editSmsConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          const res = await productSmsUpdate(this.form)
          if (res.code === 1) {
            this.$message.success(this.$t('修改成功'))
            this.getTableData()
            this.visibleEdit = false
          }
        }
      })
    },
    async copySmsConfirm() {
      if (this.selectProductList.length <= 0) return this.$message.error(this.$t('请选择APP'))
      const res = await productSmsCopy({
        productNameList: this.selectProductList,
        ids: this.selectSmsRows.map(item => item.id)
      })
      if (res.code === 1) {
        this.$message.success(this.$t('操作成功'))
        this.visibleCopySms = false
        this.selectSmsRows = []
        this.getTableData()
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    }
  },
  beforeDestroy() {
    this.$emit('update:visibleBindSms', false)
  }
}
</script>

<style lang="less" scoped>
.smsInsertVisible {
  border-radius: 4px;
  background-color: #ffffff;
  text-align: left;
  box-sizing: border-box;
  margin-right: 20px;
  z-index: 3000;

  ul {
    list-style: none;
    margin: 0;
    padding: 0;
    max-height: 300px;
    overflow-y: auto;

    li {
      font-size: 14px;
      padding: 5px 10px;
      cursor: pointer;
      width: 120px;
      border-bottom: 1px solid #eeeeee;
    }

    li:hover {
      background-color: #f0f2f5;
      color: #F1B901;
    }
  }
}
</style>
